//
//  AreaViewController.m
//  YouGoWeGo
//
//  Created by LiuFei on 14/11/19.
//  Copyright (c) 2014年 LiuFei. All rights reserved.
//

#import "AreaViewController.h"

#import "PicViewController.h"
#import "TravelViewController.h"

#import "CustomPicCollectionCell.h"
#import "CustomTipTableCell.h"
#import "CustomTravelCollectionCell.h"
#import "AreaModel.h"
#import "TravelModel.h"
#import "UIImageView+WebCache.h"

#import "MJRefresh.h"

@interface AreaViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate, UISearchBarDelegate>

@property (readwrite, nonatomic, retain) REMenu *menu;
@property (assign, nonatomic) NSInteger flag;

@end

@implementation AreaViewController

- (void)dealloc
{
    [_mySearchBar release];
    [_picButton release];
    [_tripButton release];
    [_tripButton release];
    [_picCollect release];
    [_travCollect release];
    [_tipTable release];
    [_scroll release];
    
    [_myArr release];
    [_myTempArr release];
    [_picArray release];
    [_travArray release];
    [_tipArray release];
    
    [_areaData release];
    [super dealloc];
}


- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        self.picArray = [NSMutableArray array];
        self.travArray = [NSMutableArray array];
        self.tipArray = [NSMutableArray array];
        self.myArr = [NSMutableArray array];
        self.myTempArr = [NSMutableArray array];

        self.areaData = [NSMutableData data];
        self.pInfoArray = [NSMutableArray array];
        
        self.count_1 = 8;
        self.flag = 0;
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view setBackgroundColor:[UIColor whiteColor]];
    self.navigationController.navigationBar.translucent = NO;
    [self.navigationItem setTitle:@"热门景点"];
    
    
    [self createButton];
    [self createScroll];
    [self startRequestForPic];
    [self startRequestForTrav];
    [self startRequestForTips];
    [self createPicCollect];
    [self createTravCollection];
    [self createTipTable];
    
    [self setupRefresh];
    [self createSearchBar];
}

#pragma mark - 景点图片网络获取
- (void)startRequestForPic
{
//    [ConnectModel getConnectGetWithUrl:AreaUrl parms:nil block:^(NSData *data) {
//        
//        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//        NSMutableArray *arr = [dic objectForKey:@"days"];
//        NSMutableArray *sArr = [NSMutableArray array];
//
//        for (NSMutableDictionary *sDic in arr) {
//            for (NSMutableDictionary *ssDic in [sDic objectForKey:@"waypoints"]) {
//                
//                AreaModel *model = [[AreaModel alloc] init];
//                [model setValuesForKeysWithDictionary:ssDic];
//                
//                [sArr addObject:model];
//                [model release];
//            }
//            [self.picArray addObject:sArr];
//        }
//        
//        [_picCollect reloadData];
//    }];
    
    
    NSURL *url = [NSURL URLWithString:@"http://api.breadtrip.com/destination/place/3/205/photos/?count=22&gallery_mode=true"];
    
    NSURLRequest *requsest = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:requsest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    
        self.areaData = (NSMutableData *)data;
        self.myArr = [dic objectForKey:@"items"];

        for (NSMutableDictionary *sDic in _myArr) {
            
            NSMutableDictionary *pInfo = [sDic objectForKey:@"photo_info"];

            // 存储图片的宽高
            NSString *str = [pInfo objectForKey:@"h"];
            str = [NSString stringWithFormat:@"%@%@", str, [pInfo objectForKey:@"w"]];
            
            NSMutableDictionary *pDic = [NSMutableDictionary dictionary];
            [pDic setObject:str forKey:@"photo_info"];
            [self.pInfoArray addObject:pDic];
            
            AreaModel *model = [[AreaModel alloc] init];
            [model setValuesForKeysWithDictionary:sDic];
            
            [_picArray addObject:model];
            [model release];
            }
        
        [_picCollect reloadData];
    }];
}

#pragma mark - 旅行地网络获取
- (void)startRequestForTrav
{
    NSURL *url = [NSURL URLWithString:@"http://api.breadtrip.com/destination/place/3/205/pois/sights/?count=20"];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        self.myTempArr = [dic objectForKey:@"items"];
        for (NSMutableDictionary *sDic in _myTempArr) {
            
            AreaModel *model = [[AreaModel alloc] init];
            [model setValuesForKeysWithDictionary:sDic];
            
            [self.travArray addObject:model];
            [model release];
        }
        
        [_travCollect reloadData];
    }];
    
}

#pragma mark - 小贴士网络获取
- (void)startRequestForTips
{
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://api.breadtrip.com/destination/place/3/205/tips/?count=5&start=%ld", _count_1]];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSMutableArray *tipArray = [dic objectForKey:@"tips"];
//        for (int i = 0; i < [tipArray count]; i ++) {
//            if (i > 8) {
                [self.tipArray addObjectsFromArray:tipArray];
//            }
//        }
        
        [_tipTable reloadData];
    }];
    
}

#pragma mark - 搜索栏
- (void)createSearchBar
{
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 80, 40)];
    [button setTitle:@"Search" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(search:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    [button release];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    
}

#pragma mark - 创建Button
- (void)createButton
{
    self.picButton = [[UIButton alloc] initWithFrame:CGRectMake(40, 10, self.view.frame.size.width / 5 - 10, self.view.frame.size.height / 12 - 20)];
    [_picButton setBackgroundColor:[UIColor redColor]];
    [_picButton setAlpha:1];
    [_picButton.layer setBorderWidth:0.5];
    [_picButton.layer setCornerRadius:10];
    [_picButton setTitle:@"图片" forState:UIControlStateNormal];
    [_picButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_picButton setTag:1001];
    
    [_picButton addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_picButton];
    [_picButton release];
    
    self.tripButton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 3 + 30, 10, self.view.frame.size.width / 5 - 10, self.view.frame.size.height / 12 - 20)];
    [_tripButton.layer setBorderWidth:0.5];
    [_tripButton.layer setCornerRadius:10];
    [_tripButton setBackgroundColor:[UIColor whiteColor]];
    [_tripButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_tripButton setTitle:@"旅行地" forState:UIControlStateNormal];
    [_tripButton setTag:1002];
    [_tripButton addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_tripButton];
    [_tripButton release];
    
    self.tipsButton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 3 * 2 + 20, 10, self.view.frame.size.width / 5 - 10, self.view.frame.size.height / 12 - 20)];
    [_tipsButton.layer setBorderWidth:0.5];
    [_tipsButton.layer setCornerRadius:10];
    [_tipsButton setBackgroundColor:[UIColor whiteColor]];
    [_tipsButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_tipsButton setTitle:@"小贴士" forState:UIControlStateNormal];
    [_tipsButton setTag:1003];
    [_tipsButton addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_tipsButton];
    [_tipsButton release];
    
}

#pragma mark - 创建UIScrollView
- (void)createScroll
{
    self.scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height / 12, self.view.frame.size.width, self.view.frame.size.height - _picButton.frame.size.height - 64)];
    
    [_scroll setContentSize:CGSizeMake(_scroll.frame.size.width * 3, _scroll.frame.size.height)];
    [_scroll setTag:10086];
    [_scroll setDelegate:self];
    [_scroll setPagingEnabled:YES];
    [_scroll setAlwaysBounceHorizontal:NO];
    [_scroll setBackgroundColor:[UIColor whiteColor]];
    [_scroll setShowsVerticalScrollIndicator:NO];
    [_scroll setScrollEnabled:YES];
    [self.view addSubview:_scroll];
    [_scroll release];
}


#pragma mark - 创建UICollectionView--图片页面/旅行界面
- (void)createPicCollect
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    self.picCollect = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - _picButton.frame.size.height - 64) collectionViewLayout:layout];
    
    [layout setItemSize:CGSizeMake(100, 120)];
    [layout setSectionInset:UIEdgeInsetsMake(10, 0, 20, 20)];
    
    [_picCollect setDataSource:self];
    [_picCollect setDelegate:self];
    
    [_picCollect setTag:10001];
    [_picCollect registerClass:[CustomPicCollectionCell class] forCellWithReuseIdentifier:@"picPool"];
    [_picCollect setPagingEnabled:NO];
    
    [_picCollect setBackgroundColor:[UIColor colorWithRed:137 / 255.0 green:157 / 255.0 blue:192 / 255.0 alpha:1]];
    [self.scroll addSubview:_picCollect];
    [_picCollect release];
    [layout release];
}

- (void)createTravCollection
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    self.travCollect = [[UICollectionView alloc] initWithFrame:CGRectMake(self.view.frame.size.width, 0, self.view.frame.size.width, self.view.frame.size.height - _picButton.frame.size.height - 64) collectionViewLayout:layout];
    
    [layout setItemSize:CGSizeMake(140, 140)];
    [layout setSectionInset:UIEdgeInsetsMake(30, 30, 20, 30)];
    [_travCollect setDataSource:self];
    [_travCollect setDelegate:self];
    [_travCollect setTag:10002];
    [_travCollect registerClass:[CustomTravelCollectionCell class] forCellWithReuseIdentifier:@"travelPool"];
    [_travCollect setPagingEnabled:NO];
    
    [_travCollect setBackgroundColor:[UIColor colorWithRed:137 / 255.0 green:190 / 255.0 blue:178 / 255.0 alpha:1]];
    [self.scroll addSubview:_travCollect];
    [_travCollect release];
    [layout release];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    switch (collectionView.tag) {
        case 10001:
        {
            return [_picArray count];;
        }
            break;
        case 10002:
        {
            return [_travArray count];
        }
        default:
            break;
    }
    return 0;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    switch (collectionView.tag) {
        case 10001:
        {
            CustomPicCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"picPool" forIndexPath:indexPath];
        
            AreaModel *model = [_picArray objectAtIndex:indexPath.item];
            
            cell.model = model;

            return cell;
        }
            break;
        case 10002:
        {
            CustomTravelCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"travelPool" forIndexPath:indexPath];
            
            AreaModel *model = [_travArray objectAtIndex:indexPath.item];
            cell.model = model;
            return cell;
        }
        default:
            break;
    }
    
    return nil;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    switch (collectionView.tag) {
        case 10001:
        {
            
            PicViewController *picVC = [[PicViewController alloc] init];
            
            NSMutableDictionary *dic = [_myArr objectAtIndex:indexPath.item];
            
            picVC.trip_id = [dic objectForKey:@"trip_id"];
            picVC.text = [dic objectForKey:@"text"];
        
            picVC.picData = self.areaData;
            picVC.albumArray = self.myArr;
            picVC.pInfoArray = self.pInfoArray;
            picVC.pInfoDic = [self.pInfoArray objectAtIndex:indexPath.item];
            [self.navigationController pushViewController:picVC animated:YES];
            [picVC view];
            [picVC.bigScroll setContentOffset:CGPointMake(indexPath.item * self.view.frame.size.width, 0)];

            [picVC release];
        }
            break;
        case 10002:
        {
            TravelViewController *travVC = [[TravelViewController alloc] init];
            
            NSMutableDictionary *dic = [_myTempArr objectAtIndex:indexPath.item];
            travVC.travId = [[dic objectForKey:@"id"] integerValue];

            [self.navigationController pushViewController:travVC animated:YES];
//            [travVC release];
        }
            break;
        default:
            break;
    }
}

#pragma mark - 创建小贴士页面tableview
- (void)createTipTable
{
    self.tipTable = [[UITableView alloc] initWithFrame:CGRectMake(self.view.frame.size.width * 2, 0, self.view.frame.size.width, self.view.frame.size.height - 49 - 64) style:UITableViewStylePlain];
    
    [_tipTable setDelegate:self];
    [_tipTable setDataSource:self];
    [_tipTable setBackgroundColor:[UIColor colorWithRed:201 / 255.0 green:214 / 255.0 blue:231 / 255.0 alpha:1]];
    [_tipTable setSeparatorStyle:UITableViewCellSeparatorStyleNone];
//    [_tipTable setRowHeight:200];
    [_tipTable setBackgroundColor:[UIColor whiteColor]];
    
    [self.scroll addSubview:_tipTable];
    [_tipTable release];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
    NSMutableDictionary *dic = [_tipArray objectAtIndex:indexPath.row];
    [label setText:[dic objectForKey:@"content"]];
    
    
    NSDictionary *dicc = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:16], NSFontAttributeName, nil];
    
    CGRect rect = [label.text boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width - 10, 400) options:NSStringDrawingUsesLineFragmentOrigin attributes:dicc context:nil];
    
    [label setFrame:CGRectMake(10, 0, self.view.frame.size.width - 20, rect.size.height)];
    
    return label.frame.size.height + 80;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_tipArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"tipPool";
    CustomTipTableCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[CustomTipTableCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
    }

    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    NSMutableDictionary *dic = [_tipArray objectAtIndex:indexPath.row];
    cell.userLabel.text = [[dic objectForKey:@"user"] objectForKey:@"name"];
    NSInteger count = [[dic objectForKey:@"liked_count"] integerValue];
    cell.liked_count.text = [NSString stringWithFormat:@"%ld", count];
    cell.tagLabel.text = [[[dic objectForKey:@"tags"] lastObject] objectForKey:@"name"];
    cell.timeLabel.text = [dic objectForKey:@"datetime"];
    cell.detailLabel.text = [dic objectForKey:@"content"];
    [cell.headImage setImageWithURL:[NSURL URLWithString:[[dic objectForKey:@"user"] objectForKey:@"avatar_l"]]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - 点击事件
- (void)clickAction:(id)sender
{
    UIButton *button = (UIButton *)sender;
    switch (button.tag) {
        case 1001:
        {
            
            _scroll.contentOffset = CGPointMake(0, 0);
        }
            break;
        case 1002:
        {
            [UIView beginAnimations:@"kk" context:nil];
            [UIView setAnimationDuration:0.5];
            _scroll.contentOffset = CGPointMake(_scroll.frame.size.width, 0);
            [UIView commitAnimations];

        }
            break;
        case 1003:
        {
            _scroll.contentOffset = CGPointMake(_scroll.frame.size.width * 2, 0);
        }
        default:
            break;
    }
}

- (void)search:(id)sender
{
    if (_flag == 0) {
        _mySearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
        [_mySearchBar setDelegate:self];
        [_mySearchBar setPlaceholder:@"搜索"];
        [_mySearchBar setShowsCancelButton:NO];
        
        UISearchController *search = [[UISearchController alloc] initWithSearchResultsController:self];
        
        [search setActive:NO];
        [self.view addSubview:_mySearchBar];
        [sender setTitle:@"Cancel" forState:UIControlStateNormal];
        _flag = 1;
    } else if (_flag == 1) {
        [_mySearchBar resignFirstResponder];
        [_mySearchBar removeFromSuperview];
        [sender setTitle:@"Search" forState:UIControlStateNormal];
        _flag = 0;
    }
}

#pragma mark - 滚动屏幕按钮变化颜色
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSInteger a = 0;
    if (scrollView.tag == 10086) {
        a = _scroll.contentOffset.x / self.view.frame.size.width;
        UIButton *button = (UIButton *)[self.view viewWithTag:a + 1001];
        button.backgroundColor = [UIColor redColor];
        for (UIButton *butt in self.view.subviews) {
            if (butt.tag != button.tag) {
                butt.backgroundColor = [UIColor whiteColor];
            }
        }
    }
}


#pragma mark - 上拉加载,下拉刷新
- (void)setupRefresh
{
    [self.tipTable addFooterWithTarget:self action:@selector(footerRefresh)];
    [self.tipTable setFooterReleaseToRefreshText:@"放开那个TableView, 让它加载"];
    [self.tipTable setFooterRefreshingText:@"正在加载中"];
}

- (void)footerRefresh
{
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        
        [self startRequestForTips];
        [self.tipTable reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tipTable footerEndRefreshing];
    });
    
    _count_1 ++;
    
}


@end
